/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Vue;

import Modele.Album;
import Modele.Pikasial;
import Modele.Bibliotheque;
import Modele.EnsembleImage;
import Modele.ModeleImage;
import Modele.Repertoire;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

/**
 *
 * @author Soufiane GARCH
 */
public class VuePrincipale extends JFrame implements ActionListener{
    
    private static int INIT_WIDTH = 1024;
    private static int INIT_HEIGHT = 800;
    
    private JPanel Biblio;
    private VueBibliotheque vueBiblio;
    private JScrollPane PhotoPanel;
    private JPanel Photo;
    private JList listOfPhoto;
    //private JPanel BoutonsPhoto;
    private JPanel BoutonsGeneral;
    
    private JMenuBar menu;
    private JMenuItem export;
    private JMenuItem save_Photo;
    private JMenuItem quitter;
    private JMenu fichier;
    private JMenu Diaporama;
    private JMenuItem diapo;
    private JMenu repertoire;
    private JMenuItem addRep;
    private JMenuItem supRep;
    private JMenuItem modRep;
    private JMenu album;
    private JMenuItem addAl;
    private JMenuItem supAl;
    private JMenuItem modAl;
    private JMenuItem supImage;
    
    private Bibliotheque bibliotheque;
    private Pikasial pikasial;
    private ModeleImage imageActuel = null;
    
    
    
    public VuePrincipale(){
        File fichier = new File("library.xml");
        if (fichier.exists()){
            try{
                pikasial = new Pikasial(fichier.getAbsolutePath());
                bibliotheque = pikasial.getBibliotheque();
                /*System.out.println(bibliotheque.toString());
                Vector al = bibliotheque.getAlbum();
                Iterator it = al.iterator();
                while(it.hasNext()){
                    Album a = (Album) it.next();
                    ArrayList img = a.getListImages();
                    for(int i=0; i < img.size(); i++){
                        ModeleImage mi = (ModeleImage) img.get(i);
                        System.out.println(mi.getAdresse());
                    }
                        
                }
                
                Vector rep = bibliotheque.getRepertoire();
                Iterator it2 = rep.iterator();
                while(it2.hasNext()){
                    Repertoire a = (Repertoire) it2.next();
                       System.out.println(a.getAbsoluteAdr());
                       ArrayList img = a.getImages();
                        for(int i=0; i < img.size(); i++){
                            ModeleImage mi = (ModeleImage) img.get(i);
                            System.out.println(mi.getAdresse());
                    }
                }
                
                return;*/
            }catch(Exception e){
                // Do nothing :-)
            }
        }else{
            bibliotheque = new Bibliotheque();
            pikasial = new Pikasial(bibliotheque);
        }
        
        this.setTitle("Pikasial");

        //this.setBackground(new Color(178, 212, 226));
        this.setAndaddAllJPanel();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(800, 600);
        this.centerJFrame();
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setEnabled(true);
        this.setVisible(true);
    }
    
    private void setAndaddAllJPanel(){
        this.setMenu();
        this.setJMenuBar(menu);
        
        this.setLayout(null);
        
        this.setBiblio();
        this.add(Biblio);
        
        this.setPhoto();
        this.add(Photo);
        
        this.setBoutonsGeneral();
        this.add(BoutonsGeneral);
    }
    
    
    private void centerJFrame(){
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((d.width - INIT_WIDTH)/2, (d.height - INIT_HEIGHT)/2);
    }
    
    
    private void setBiblio(){
        Biblio = new JPanel();
        Biblio.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        Biblio.setBounds(2, 2, 300, 662);
        Biblio.setVisible(true);
        //ajouter le repertoire
        //ajouter l'album
        vueBiblio = new VueBibliotheque(bibliotheque, this);
        Biblio.add(vueBiblio);
    }
    
    private void setPhoto(){
        listOfPhoto = new JList();
        listOfPhoto.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        Photo = new JPanel();
        //PhotoPanel = new JScrollPane(Photo);
        Photo.setLayout(new FlowLayout());
        Photo.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        Photo.setBounds(320, 72, 958, 870);
        //PhotoPanel.add(Photo);
        Photo.addMouseListener(new MouseListener() 
		{
			public void mouseClicked(MouseEvent e)
			{
                            if (e.getClickCount() == 1){
                                Component[] comp = Photo.getComponents();
                                for(int i=0; i<comp.length; i++){
                                    if (comp[i] instanceof VueMiniature){
                                        VueMiniature vM = (VueMiniature) comp[i];
                                        vM.recadrer(false);
                                    }
                                }
                            }
			}
			public void mouseEntered(MouseEvent e) {}
			public void mouseExited(MouseEvent e) {}
			public void mousePressed(MouseEvent e) {}
			public void mouseReleased(MouseEvent e) {}
		}
        );
    }
    
    
    private void setBoutonsGeneral(){
        BoutonsGeneral = new JPanel();
        BoutonsGeneral.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        BoutonsGeneral.setBounds(320, 2, 958, 50);
        BoutonsGeneral.add(new VueBouton(this));
    }
    
    
    private void setMenu(){
        export = new JMenuItem("Enregistrer la Bibliothéque");
        export.addActionListener(this);
        
        save_Photo = new JMenuItem("Enregistrer les modifications");
        save_Photo.addActionListener(this);
        
        quitter = new JMenuItem("Quitter");
        quitter.addActionListener(this);
        
        repertoire = new JMenu("Répertoire");
        addRep = new JMenuItem("Ajouter un répertoire");
        addRep.addActionListener(this);
        
        supRep = new JMenuItem("Supprimer un répertoire");
        supRep.addActionListener(this);
        
        modRep = new JMenuItem("Modifier un répertoire");
        modRep.addActionListener(this);
        
        repertoire.add(addRep);
        repertoire.add(modRep);
        repertoire.add(supRep);
        
        album = new JMenu("Album");
        addAl = new JMenuItem("Ajouter un album");
        addAl.addActionListener(this);
        
        supAl = new JMenuItem("Supprimer un album");
        supAl.addActionListener(this);
        
        modAl = new JMenuItem("Modifier un album");
        modAl.addActionListener(this);
        
        supImage = new JMenuItem("Supprimer l'image de l'album");
        supImage.addActionListener(this);
        
        album.add(addAl);
        album.add(modAl);
        album.add(supAl);
        //album.add(supImage);
        
        
        fichier = new JMenu("Fichier");
        fichier.add(export);
        fichier.add(save_Photo);
        fichier.addSeparator();
        fichier.add(repertoire);
        fichier.add(album);
        fichier.addSeparator();
        fichier.add(quitter);
        
        Diaporama = new JMenu("Diaporama");
        diapo = new JMenuItem("Lancer le diaporama");
        Diaporama.add(diapo);
        diapo.addActionListener(this);
        
        menu = new JMenuBar();
        menu.add(fichier);
        menu.add(Diaporama);
    }
    
    public VueBibliotheque getBiblio(){
        return this.vueBiblio;
    }
    
    public void afficheMiniature(EnsembleImage ensImg){
        Photo.removeAll();
        Photo.validate();
        Photo.repaint();
        ArrayList listOfImg = ensImg.getListofImage();
        Iterator it = listOfImg.iterator();
        while(it.hasNext()){
            ModeleImage img = (ModeleImage) it.next();
            VueMiniature vImgM = new VueMiniature(img, this);
            vImgM.validate();
            Photo.add(vImgM);
            System.out.println("Affichage de : " + vImgM.getNom());
            Photo.validate();
            //PhotoPanel.repaint();
            this.getContentPane().validate();
            this.validate();
        }
        Photo.validate();
        this.getContentPane().validate();
        this.validate();
    }

    @Override
    public void repaint() {
        super.repaint();
    }
    public JPanel getPanelPhoto(){
        return Photo;
    }
    public void afficheImage(ModeleImage mI){
        Photo.removeAll();
        this.imageActuel = mI;
        //VueImagePane iPane = new VueImagePane(mI);
        VueImage iPane = new VueImage(mI);
        iPane.validate();
        Photo.add(iPane);
        Photo.validate();
        //PhotoPanel.repaint();
        this.getContentPane().validate();
        this.validate();
        System.out.println("Affichage de : " + mI.getNom() + " seulement");
    }
    
    public void setImageActuel(ModeleImage im){
        this.imageActuel = im;
    }
    
    public ModeleImage getImageActuel(){
        return this.imageActuel;
    }
    
    @SuppressWarnings("static-access")
    public void actionPerformed(ActionEvent e) {
        
        Object source = e.getSource();
        if (source == quitter){
            //save biblio
            System.exit(0);
        }
        else if (source == addRep){
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("."));
            chooser.changeToParentDirectory();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            
            if(chooser.showOpenDialog(null)==JFileChooser.CANCEL_OPTION)
                return;
            String adr = chooser.getSelectedFile().getAbsolutePath();
            if (bibliotheque.existeRep(adr)){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Repértoire déjà ajouté","Ajout de répertoire",JOptionPane.WARNING_MESSAGE);        
                return;
            }
            Repertoire rep = new Repertoire(adr);
            this.vueBiblio.ajouterRepertoire(rep);
            bibliotheque.ajouterRepertoire(rep);
        }
        else if (source == modRep){
            Repertoire rep = vueBiblio.getRepertoireActuel();
            if (rep == null){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucun répertoire selectionné","Renommer un répertoire",JOptionPane.WARNING_MESSAGE);
            }else{
                JOptionPane d = new JOptionPane();
                String nom;
                nom = d.showInputDialog(this,"Donner un nouveau nom","Nouveau Dossier");
                if (nom != null){
                    rep.modifierNom(nom);
                    vueBiblio.getVueRepertoire().getList().repaint();
                }                    
            }
        }
        else if (source == supRep){
            Repertoire rep = vueBiblio.getRepertoireActuel();
            if (rep == null){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucun répertoire selectionné","Supprimer un répertoire",JOptionPane.WARNING_MESSAGE);
            }else{
                pikasial.suppressionRepertoire(rep);
                vueBiblio.getVueRepertoire().deleteRepertoire(rep);
                vueBiblio.getVueRepertoire().getList().repaint();
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Le repertoire " + rep.toString() + " a été supprimé avec succé.","Supprimer un répertoire",JOptionPane.WARNING_MESSAGE);
            }
        }
        else if (source == addAl){
            JOptionPane d = new JOptionPane();
            String nom;
            nom = d.showInputDialog(this,"Donner un nouveau nom","Nouveau Album");
            if (nom != null){
                if (bibliotheque.existeAl(nom)){
                    JOptionPane d2 = new JOptionPane();
                    d2.showMessageDialog(this,"Album déjà créé","Ajout de répertoire",JOptionPane.WARNING_MESSAGE);        
                    return;
                }
                Album al = new Album(nom);
                pikasial.ajouterAlbum(al);
                vueBiblio.ajouterAlbum(al);
                vueBiblio.getVueAlbum().getList().repaint();
            }
        }
        else if (source == modAl){
            Album al = vueBiblio.getAlbumActuel();
            if (al == null){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucun répertoire selectionné","Supprimer un répertoire",JOptionPane.WARNING_MESSAGE);
            }else{
                JOptionPane d = new JOptionPane();
                String nom;
                nom = d.showInputDialog(this,"Donner un nouveau nom","Renommer");
                if (nom != null){
                    al.modifierNom(nom);
                    vueBiblio.getVueAlbum().getList().repaint();
                }                    
            }
        }
        else if(source == supAl){
            Album al = vueBiblio.getAlbumActuel();
            if (al == null){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucun Album selectionné","Supprimer un album",JOptionPane.WARNING_MESSAGE);
            }else{
                pikasial.suppressionAlbum(al);
                vueBiblio.getVueAlbum().deleteAlbum(al);
                vueBiblio.getVueAlbum().getList().repaint();
                JOptionPane d = new JOptionPane();
                Photo.removeAll();
                Photo.repaint();
                d.showMessageDialog(this,"L'album " + al.toString() + " a été supprimé avec succé.","Supprimer un répertoire",JOptionPane.WARNING_MESSAGE);
            }
        }else if(source == export){
                try{
                    bibliotheque.saveLibrary();
                    JOptionPane d = new JOptionPane();
                    d.showMessageDialog(this,"Bibliothéque sauvegardée.","Pikasial",JOptionPane.WARNING_MESSAGE);
                }catch(IOException ioe){
                    System.out.println("Erreur de parseur XML");
                }
        }else if (source == save_Photo){
            if (this.imageActuel == null){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucune image selectionnée","Traitement image",JOptionPane.WARNING_MESSAGE);        
                return;
            }
            try{
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }catch(Exception exc) {
                System.err.println("Error loading L&F: "+exc);
            }
				
            JFileChooser filechooser = new JFileChooser();
		
            filechooser.setAcceptAllFileFilterUsed(false);
            filechooser.setDialogTitle("Enregistrer ...");
            String ext = imageActuel.getExtention();
            String desc = "Image " + imageActuel.getExtention().toUpperCase();
            
            filechooser.setFileFilter(new Filtre(desc, ext));
            int choix = filechooser.showSaveDialog(this);
            
	               
            if(choix == JFileChooser.APPROVE_OPTION){
                File file = filechooser.getSelectedFile();
                File tmp = new File(file.getAbsolutePath());
                
                if (tmp.exists()){
                    JOptionPane d = new JOptionPane();
                    d.showMessageDialog(this,"Le fichier existe déjà.","Traitement image",JOptionPane.WARNING_MESSAGE);        
                    return;
                }
                
                try{
                    this.imageActuel.enregistrerModificaions(file.getAbsolutePath() + "." + ext);
                    JOptionPane d = new JOptionPane();
                    d.showMessageDialog(this,"Sauvegarde effectué","Traitement image",JOptionPane.WARNING_MESSAGE);        
                    return;
                }catch(IOException ioe_save){
                    System.out.println("Erreur de sauvegarde");
                    JOptionPane d2 = new JOptionPane();
                    d2.showMessageDialog(this,"Erreur inconnu de sauvegarde","Traitement image",JOptionPane.WARNING_MESSAGE);        
                    return;
                }
            }
	
            try{
		UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            }catch(Exception exc){
                System.err.println("Error loading L&F: "+exc);
            }
	    //enregistrerModificaions
        }else if(source == diapo){
            if ( (vueBiblio.getAlbumActuel() == null) && (vueBiblio.getRepertoireActuel() == null)){
                JOptionPane d = new JOptionPane();
                d.showMessageDialog(this,"Aucune album ni aucun repertoire selectionné","Pikasial",JOptionPane.WARNING_MESSAGE);        
                return;
            }           
            if (vueBiblio.getAlbumActuel() == null){
                VueDiaporama diapo = new VueDiaporama(vueBiblio.getRepertoireActuel().getListofImage());
                return;
            }
            if (vueBiblio.getRepertoireActuel() == null){
                VueDiaporama diapo = new VueDiaporama(vueBiblio.getAlbumActuel().getListofImage());
                return;
            }
        }
    
    }
    
    
    
    
    
    
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            	new VuePrincipale();
            }
        });
    }
}
